package cn.hzking.gjmall.delegates.my;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fingdo.statelayout.StateLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.MainActivity;
import cn.hzking.gjmall.activitys.order.PaySuccessActivity;
import cn.hzking.gjmall.adpters.order.OrderAdapter;
import cn.hzking.gjmall.base.BaseSecondDelegate;
import cn.hzking.gjmall.bean.OrderBean;
import cn.hzking.gjmall.bean.event.OrderStateChangeBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseEntity;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.net.base.GjCustomStateViewObserver;
import cn.hzking.gjmall.utils.UIUtils;

/**
 *
 */
public class OrderDelegate extends BaseSecondDelegate implements OrderAdapter.Operation{
    public static final int TOTLEORDER = 0;
    public static final int WAITPAY = 1;
    public static final int WAITSEND = 2;
    public static final int WAITRECIVE = 3;
    public static final int COLSED = 4;
    public static final int BACKMONEY = 5;
    public static final int COMPLETE = 6;
    public static final String FRAGMENTID = "fragmentId";
    @Bind(R.id.recyclerview) RecyclerView recyclerview;
    @Bind(R.id.refrsh) SwipeRefreshLayout refrsh;
    @Bind(R.id.statlayout) StateLayout statlayout;
    private int fragmentId;
    private int page=1;
    private String status="";
    OrderAdapter orderAdapter;
    public OrderDelegate() {
    }

    public static OrderDelegate newInstance(int param1) {
        OrderDelegate fragment = new OrderDelegate();
        Bundle args = new Bundle();
        args.putInt(FRAGMENTID, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            fragmentId = getArguments().getInt(FRAGMENTID);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.fragment_order_delegate;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(_mActivity);
        recyclerview.setLayoutManager(linearLayoutManager);
        orderAdapter = new OrderAdapter(R.layout.item_order, null);
        orderAdapter.setOperation(this);
        recyclerview.setAdapter(orderAdapter);
        refrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        orderAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                getNetData(status,false,false,false,true,null,null);
            }
        },recyclerview);
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int topRowVerticalPosition = (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                refrsh.setEnabled(topRowVerticalPosition >= 0);
            }
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });
    }

    private void refresh() {
        page=1;
        getNetData(status,false,true,false,true,null,null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void onEvent(OrderStateChangeBean bean) {
        OrderStateChangeBean stickyEvent = EventBus.getDefault().removeStickyEvent(OrderStateChangeBean.class);
        if(stickyEvent != null) {
            if(bean!=null){
                if(!TextUtils.isEmpty(bean.getState())){
                    if(bean.getState().equals("statechange")){
                        page=1;
                        getNetData(status,false,true,false,true,null,null);
                    }
                }
            }
        }
    }


    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        //加载数据
        switch (fragmentId){
            case TOTLEORDER:
                status="";
                break;
            case WAITPAY:
                status="WAIT_BUYER_PAY";
                break;
            case WAITSEND:
                status="WAIT_SEND_GOODS";
                break;
            case WAITRECIVE:
                status="ALREADY_SEND";
                break;
            case COLSED:
                status="TRADE_CLOSED";
                break;
            case BACKMONEY:
                status="REFUNDED_CLOSED";
                break;
            case COMPLETE:
                status="TRADE_FINISHED";
                break;
            default:
                    break;
        }
        getNetData(status,true,false,true,true,null,null);
    }


    public void getNetData(String status, boolean isFristInit, boolean isRefrsh, boolean isShowDialog, boolean isCancel, View onNetView, View errorView) {
        HashMap<String, String> parms = new HashMap<>();
        parms.put("status",status);
        parms.put("page",String.valueOf(page));
        RetrofitFactory.getInstant().API()
                .getOrderList(parms)
                .compose(this.<OrderBean>setThread())
                .subscribe(new GjCustomStateViewObserver<OrderBean>(_mActivity,statlayout,refrsh,isFristInit,isRefrsh,isShowDialog,isCancel,null,onNetView,errorView) {
                    @Override
                    protected void onBusinessSuccess(OrderBean orderBean) throws Exception {
                        if(orderBean!=null){
                            List<OrderBean.DataBean.OrderListBean.ModuleBean> list=orderBean.getData().getOrderList().getModule();
                            if(page==1){
                                orderAdapter.setNewData(list);
                                if(orderAdapter.getData().size() == 0){
                                    View view = View.inflate(_mActivity,R.layout.layout_statelayout_custom_order_empty,null);
                                    TextView gobuyTv=view.findViewById(R.id.tv_gobuy);
                                    gobuyTv.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            EventBus.getDefault().post("goHome");
                                            Intent intent = new Intent(_mActivity, MainActivity.class);
                                            startActivity(intent);
                                        }
                                    });
                                    statlayout.showCustomView(view);
                                    return;
                                }
                            }else {
                                orderAdapter.addData(list);
                            }
                            page++;
                        }
                        if (orderBean.getData().getOrderList().getTotalRecord() == orderAdapter.getData().size()) {//数据加载完成
                            orderAdapter.loadMoreEnd(false);
                        } else {
                            orderAdapter.loadMoreComplete();
                        }
                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }

                    @Override
                    protected void onBusinessFail(OrderBean orderBean) {
                        super.onBusinessFail(orderBean);
                        UIUtils.showToastShort(_mActivity,orderBean.getErrorMsg());
                    }
                });
    }

    @Override
    public void delete(int orderId) {//删除订单
        createDialog("您是否删除该订单?",orderId,1);
    }
    public void createDialog(String title, final int orderId, final int type) {
        View view = LayoutInflater.from(_mActivity).inflate(R.layout.dialog_order, null);// 得到加载view
        TextView titleTv=view.findViewById(R.id.tv_title);
        TextView cancelTv=view.findViewById(R.id.tv_cancel);
        TextView sureTv=view.findViewById(R.id.tv_sure);
        titleTv.setText(title);
        final Dialog orderDialog = new Dialog(_mActivity, R.style.mydialog);// 创建自定义样式dialog
        orderDialog.setCanceledOnTouchOutside(false);
        orderDialog.setCancelable(false);
        orderDialog.setContentView(view);
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
            }
        });
        sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orderDialog.dismiss();
                if(type==1){
                    delOrder(orderId);
                }else if(type==2){
                    sureOrder(orderId);
                }
            }
        });
        orderDialog.show();
    }
    private void delOrder(int orderId){
        RetrofitFactory.getInstant().API()
                .deleteOrder(orderId)
                .compose(this.<BaseEntity>setThread())
                .subscribe(new BaseObserver<BaseEntity>(_mActivity,true,true) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        page=1;
                        getNetData(status,false,false,false,true,null,null);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(_mActivity,baseEntity.getErrorMsg());
                    }
                });
    }

    private void sureOrder(int orderId){
        RetrofitFactory.getInstant().API()
                .sureReceive(orderId)
                .compose(this.<BaseEntity>setThread())
                .subscribe(new BaseObserver<BaseEntity>(_mActivity,true,true) {
                    @Override
                    protected void onSuccees(BaseEntity baseEntity) throws Exception {
                        page=1;
                        getNetData(status,false,false,false,true,null,null);
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {

                    }

                    @Override
                    protected void onCodeError(BaseEntity baseEntity) throws Exception {
                        super.onCodeError(baseEntity);
                        UIUtils.showToastShort(_mActivity,baseEntity.getErrorMsg());
                    }
                });
    }

    @Override
    public void sure(int orderId) {//确认收货
        createDialog("您是否确认收货?",orderId,2);
    }
}
